package org.devops

class Harbor {
    // 镜像构建推送方法
    def BuildImage(script,credentialsId, harborUrl, projectGroup, imageName, imageTag) {
        script.withCredentials([
            script.usernamePassword(
            credentialsId: credentialsId,
            usernameVariable: 'HARBOR_USER',
            passwordVariable: "HARBOR_PASSWORD"
            )
        ]) {
            try {
                // Docker登录
                script.sh """
                    echo "\${HARBOR_PASSWORD}" | \
                    docker login "${harborUrl}" \
                        -u "\${HARBOR_USER}" \
                        --password-stdin
                """
                
                // 完整镜像地址
                def fullImageName = "${harborUrl}/${projectGroup}/${imageName}:${imageTag}"
                
                // 构建镜像
                script.sh "docker build -t ${fullImageName} ."
                
                // 推送镜像
                script.sh "docker push ${fullImageName}"
                
                // 清理本地镜像
                script.sh "docker rmi ${fullImageName}"
                
                return fullImageName
            } catch (Exception e) {
                script.error "镜像构建失败: ${e}"
            }
        }
    }
}